#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#pyversion:python3.5
#owner:fuzj

import json
import time
import datetime

menu = {
    '历史订单':"",
    '余额':{
        '查看余额': "",
        '充值余额': "",
    },
    '开始购物':{
            'Electronic':[
                ("Macbook Pro",10000),
                ("Macbook Air",7000),
                ("iphone",5000)
            ],
            'Car': [
                ("Tesla",800000),
                ("audi A6",600000),
                ("tiguan",300000)
            ],
            'Clothing':[
                ("Armani",32000),
                ("LV",12000),
                ("UNIQLO",2000)
            ]
    }
}

def Menu(info):
    ext = ["Already buy","back","quit"]     #将back 和quit 存到列表
    menu = {}               #定义一个空的mene字典，用来存放选项数字和选项的对应关系
    key = list(sorted(info)) + ext     #合并形成完整的菜单列表
    for k, v in enumerate(key,start=1):
        print(k,'.', v)                    #输出菜单项
        menu[str(k)] = v                #将选项数字和选项的对应关系存字典
    for i in range(3):
        if i < 3:
            rs = str(input("Your Choose: "))    #用户输入
            if rs in menu:              # 判断用户输入的数字是否在选项中
                return menu[rs]
            else:
                print('''Input Error,Please Select Right option !!!
                You have %s chance....''' % (2-i))
        else:
            print("Input Too manay error,go away!!!")
            return "quit"

def get_UserInfo():
    try:
        fp = open('shopdb','r')                    #读取用户信息文件
    except:
        print("No shopdb file")
    username = input("Your Name: ")
    password = input("Your Password: ")
    for i in fp.readlines():                #循环读取每个用户信息
        info = json.loads(i)                    #将json格式的字符串转换为字典
        name = info['username']               #取出用户名
        passwd = info['password']               #取出用户密码
        enable = info['enable']                 #取出用户状态
        if username == name:                    #判断用户名是否正确
            if enable == "1":                   #判断用户是否启用，启用则返回用户信息，禁用则提示用户，并退出
                for i in range(2):             #设置用户只有三次输入密码机会
                    if passwd == password:            #判断用户密码是否正确，正确则返回用户信息，否则重新输入
                        return info
                    else:
                        print("Password is invalid...")
                        password = input("Your Password: ")
                print("Too Manay Input, You are so stupid...")  # 完成上面循环，说明用户输入次数超过3此，退出及禁用该用户
                info['enable'] = "0"   #将用户设置为禁用
                SaveDB(info)       #写入shopdb文件
                exit()
            else:
                print("User %s is disabled,Please contact administrator..." % username)
                exit()
    #上面循环没有匹配到用户，说明该用户不存在，下面开始进行注册流程
    print("No this user,Please register... ")
    print("Shopping User Register".center(50,'='))
    for i in range(2):          #用户输入次数限制为3次
        username = input("Your Name: ")
        password1 = input("Your Password: ")
        password2 = input("Your Password again: ")
        if password1 == password2:   #比较两次输入的密码。若相同则返回新用户的信息，余额默认一百万
            info = {'username':username,'password':password,'enable': "1",'balance':1000000,'Shopping Cart':[]}
            fw = open('shopdb','a')         #将新注册的用户写入shopdb文件
            fw.write(json.dumps(info)+'\n')
            fw.close()
            print("User %s Register is successfull, default balance 1000000,please enjoy it.." % username)
            return info
        else:               #如果两次输入密码不一样，则继续循环，重新输入
            print("Entered passwords differ!!!")
    print("Too Manay Input, You are so stupid...")    #完成上面循环，说明用户输入次数超过3此，退出
    exit()

def buy(shoping,num):                          #定义一个购买商品的函数
    shop_name = shoping[0]                 #取出购买的商品名字
    shop_price = shoping[1]                #取出购买的商品价格
    balance = userinfo['balance']           #从userinfo字典里取出当前余额
    timestamp = int(time.time())                #记录本次本商品购买时间
    if balance >= shop_price * num:         #余额大于 商品单件*数量 ,可以购买
        userinfo['balance'] = balance - shop_price * num       #购买之后,余额减少
        shop = {'wares':shop_name,'price':shop_price,'date':timestamp}   #将商品组成商品字典
        for i in range(num):
            userinfo['Shopping Cart'].append(shop)   #将商品字典加入到userinfo的购物车中
            current_shop.append(shop)
        print("Added the product [%s], your current balance is [%s]" % (shop_name,userinfo['balance']))
    else:
        print("your balance is [%s], can't afford the [%s]" % (balance, shop_name))
        rs = input("do you want to Prepaid balance? y/n ")
        if rs == 'yes' or rs == 'y':
            Balance("Recharge")
        elif rs == "no" or rs == "n":
            pass
        else:
            print("The data type is invaild...")

def HistoricalOrder(ShopCart):    #定义一个查看订单的函数
    WaresList = []         #此列表用于存商品名称,以便后面统计数量
    timestamplist = {}    #此字典用于存放商品和购买时间，以便时间比较，取最晚的时间
    for i in ShopCart:
        WaresList.append(i['wares'])        #将商品名称加入列表
        if i['wares'] in timestamplist:
            if int(i['date']) > int(timestamplist[i['wares']]):
                timestamplist[i['wares']] = i['date']
        else: 
            timestamplist[i['wares']] = i['date']
    print("Your purchase record...")
    print("HistoricalOrder".center(60,"*") )       #打印商品名称
    for m in set(WaresList): #循环商品列表.并且使用set()函数去重
        print("商品:%s  数量:%s    最后一次购买时间:%s" %(m,WaresList.count(m),time.strftime("%Y-%m-%d %H:%M:%S", time.localtime( float(timestamplist[m])))))
    print("END".center(60,"*"))

def Balance(option):      #定义一个余额的操作函数,功能为充值和查看
    if option == "Recharge":    #判断用户的操作类型,Recharge 表示充值
        print("Your Balance is %s Now..." % userinfo['balance'])
        rs = input("how many do you want to recharge? ")
        if rs.isdigit() and int(rs) > 0:  # 判断用户输入是否合法
            userinfo['balance'] += int(rs)          #修改userinfo中余额key,用户余额加充值金额
            print("Recharge is successfull,now balance is %s" % userinfo['balance'])
        else:
            print("The data type is invaild...")
    elif option == "Select":   #判断用户的操作类型,Select 表示查询
        print("Your Balance is %s Now..." % userinfo['balance'])
    else:
        print("No this option")

def SaveDB(data):
    try:
        fp = open('shopdb','r').readlines()        #读取用户信息文件
        fw = open('shopdb', 'w')
    except:
        print("No shopdb file")
    for i in fp:
        i = json.loads(i)    #将读取的信息转换成一个字典
        if data['username'] == i['username']:    #本次循环的用户是否是当前用户,如果是的话,将重新赋值并写入
            i = data
        fw.write(json.dumps(i)+'\n')
    fw.close()

def main():
    global userinfo,current_shop   #将
    userinfo=get_UserInfo()    #存储用户整个信息表
    current_shop = []  # 定义一个列表.用于存储当前购买的商品


    tag = 1                   #初始化标签
    while True:
        if tag == 1:              #表示一级菜单
            menu01 = Menu(menu)
            if menu01 == "back":   #判断返回值，一级菜单返回的话直接退出
                HistoricalOrder(current_shop)     #退出时打印本次购买的商品
                print("Byle...")
                SaveDB(userinfo)
                exit()
            elif menu01 == "quit":   #判断返回值，quit 表示退出
                HistoricalOrder(current_shop)      #退出时打印本次购买的商品
                print("Byle...")
                SaveDB(userinfo)
                exit()
            elif menu01 == "历史订单":
                HistoricalOrder(userinfo['Shopping Cart'])
            elif menu01 == "Already buy":   #查看本次购买的所有商品
                HistoricalOrder(current_shop)
            else:
                tag += 1               #若显示完一级菜单，默认进行显示二级菜单，tag+1
        if tag == 2:             #二级菜单继续
            menu02 = Menu(menu[menu01])
            if menu02 == "back":   #判断返回值， 若为back，则返回一级菜单，tag初始化为1
                tag = 1
                continue                    #跳过此次循环
            elif menu02 == "quit":        #判断返回值，quit 表示退出
                HistoricalOrder(current_shop)      #退出时打印本次购买的商品
                print("Byle...")
                SaveDB(userinfo)
                exit()
            elif menu02 == "Already buy":    #查看本次购买的所有商品
                HistoricalOrder(current_shop)
            elif menu02 == "充值余额":         #用户选项为充值余额时,调用余额的函数
                Balance("Recharge")
            elif menu02 == "查看余额":       #用户选项为查看余额时,调用余额函数
                Balance("Select")
            else:
                tag += 1                     #若显示完二级菜单，默认进行显示三级菜单，tag+1
        if tag == 3:
            menu03 = Menu(menu[menu01][menu02])
            if menu03 == "back":         #判断返回值， 若为back，则返回二级菜单，tag初始化为2
                tag = 2
                continue                #跳过此次循环
            elif menu03 == "quit":     #判断返回值，quit 表示退出
                HistoricalOrder(current_shop)      #退出时打印本次购买的商品
                print("Byle...")
                SaveDB(userinfo)
                exit()
            elif menu03 == "Already buy":   #查看本次购买的所有商品
                HistoricalOrder(current_shop)
            else:
                num = input("How many do you want to by? ")
                if num.isdigit() and int(num) > 0:     #判断用户输入是否合法
                    buy(menu03,int(num))
                else:
                    print("The data type is invaild...")


if __name__ == "__main__":
    print("Welcome visit Shopping".center(100,'-'))
    main()
